<template>
  <view class="dialog-container">
    <!-- 左侧助手栏 -->
    <view class="sidebar">
      <view class="sidebar-header">
        <view class="sidebar-title" @tap="openAssistantPopup">新建助理</view>
        <u-button v-if="selectedAssistantIds.length > 0" type="error" size="mini" @tap="batchDeleteAssistants">删除</u-button>
      </view>
      <view class="assistant-list">
        <!-- 动态渲染助手列表 -->
        <view 
          v-for="item in assistantList" 
          :key="item.id" 
          class="assistant-item"
          :class="{ 'active': currentAssistant && currentAssistant.id === item.id }"
          @longpress="item.showContextMenu = true"
        >
          <view class="assistant-checkbox">
            <checkbox 
              :checked="selectedAssistantIds.includes(item.id)" 
              @tap.stop="toggleAssistantSelection(item.id)"
            />
          </view>
          <view class="assistant-content" @tap="selectAssistant(item)">
            <u-avatar size="small" :src="item.avatar || 'https://i.pravatar.cc/40?img=3'" />
            <view>
              <text>{{ item.name }}</text>
              <view style="font-size: 12px; color: #888;">{{ item.datasets && item.datasets.length ? item.datasets.map(d => d.name).join(', ') : '无知识库' }}</view>
            </view>
            <view class="assistant-actions">
              <button class="edit-button" @tap.stop="editAssistant(item)">编辑</button>
            </view>
          </view>
          <!-- 添加右键菜单 -->
          <u-popup v-model="item.showContextMenu" mode="bottom">
            <view class="context-menu">
              <view class="context-menu-item" @tap="editAssistant(item)">
                <text>编辑</text>
              </view>
              <view class="context-menu-item delete" @tap="deleteAssistantById(item.id)">
                <text>删除</text>
              </view>
            </view>
          </u-popup>
        </view>
        <!-- 无数据时显示提示 -->
        <view v-if="assistantList.length === 0" class="empty-assistant">
          暂无助理，点击上方"新建助理"创建
        </view>
      </view>
    </view>
    <!-- 中间会话栏 -->
    <view class="chat-list">
      <view class="chat-title">
        <text>聊天</text>
        <u-icon name="plus" size="20" color="#409EFF" />
      </view>
      <view class="chat-item active">ARMA模型是什么</view>
      <view class="chat-item">老师</view>
    </view>
    <!-- 右侧聊天内容区 -->
    <view class="chat-content">
      <view class="chat-header">
        <text class="chat-question">是什么专业的</text>
        <u-icon name="more" size="20" color="#bbb" />
      </view>
      <view class="chat-message">
        <u-avatar size="small" src="https://i.pravatar.cc/40?img=3" />
        <view class="message-bubble">
          <text>
            嗯，用户问的是"是什么专业的"，看起来您想知道的职业背景或教育相关...
          </text>
        </view>
      </view>
      <view class="chat-message self">
        <u-avatar size="small" src="https://i.pravatar.cc/40?img=4" />
        <view class="message-bubble">
          <text>{{ messageContent || '你好' }}</text>
          <!-- 显示上传的文件 -->
          <view v-if="uploadedFiles.length > 0" class="uploaded-files">
            <view v-for="(file, index) in uploadedFiles" :key="index" class="uploaded-file">
              <u-icon name="file-text" size="20" color="#409EFF"></u-icon>
              <text class="file-name">{{ file.name }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="chat-input">
        <input class="input" v-model="messageText" placeholder="消息/提问..." />
        <view class="chat-input-actions">
          <view class="upload-icon" @tap.stop.prevent="openFileSelector">
            <u-icon name="photo" size="24" color="#409EFF"></u-icon>
          </view>
          <u-button type="primary" size="small" @tap="sendMessage">发送</u-button>
        </view>
      </view>
    </view>

    <!-- 新建助理弹窗 -->
    <view v-if="showAssistantPopup" class="assistant-popup-mask">
      <view class="assistant-popup-content" @tap.stop>
        <!-- Tab栏 -->
        <view class="tab-bar">
          <view :class="['tab', activeTab === 'setting' ? 'active' : '']" @tap="activeTab = 'setting'">助理设置</view>
          <view :class="['tab', activeTab === 'prompt' ? 'active' : '']" @tap="activeTab = 'prompt'">提示引擎</view>
          <view :class="['tab', activeTab === 'model' ? 'active' : '']" @tap="activeTab = 'model'">模型设置</view>
        </view>
        <!-- Tab内容 -->
        <view v-if="activeTab === 'setting'" class="tab-content">
          <view style="padding: 24px;">
            <view class="form-row">
              <view class="form-label required">助理姓名</view>
              <u-input v-model="assistantForm.name" placeholder="例如 贾维斯简历" />
            </view>
            <view class="form-row">
              <view class="form-label">助理描述</view>
              <u-input v-model="assistantForm.description" placeholder="chat.descriptionPlaceholder" />
            </view>
            <view class="form-row">
              <view class="form-label">助理头像</view>
              <u-upload :file-list="assistantForm.avatarList" @afterRead="onAvatarUpload" :max-count="1" />
            </view>
            <view class="form-row">
              <view class="form-label">空回复 <u-icon name="question-circle" size="16" color="#bbb" style="margin-left: 4px;" /></view>
              <u-input v-model="assistantForm.emptyReply" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">设置开场白 <u-icon name="question-circle" size="16" color="#bbb" style="margin-left: 4px;" /></view>
              <u-textarea v-model="assistantForm.greeting" placeholder="你好！我是你的助理，有什么可以帮助你的吗？" />
            </view>
            <view class="form-row switch-row">
              <view class="form-label">显示引文 <u-icon name="question-circle" size="16" color="#bbb" style="margin-left: 4px;" /></view>
              <u-switch v-model="assistantForm.showCitation" />
            </view>
            <view class="form-row switch-row">
              <view class="form-label">关键词分析 <u-icon name="question-circle" size="16" color="#bbb" style="margin-left: 4px;" /></view>
              <u-switch v-model="assistantForm.keywordAnalysis" />
            </view>
            <view class="form-row switch-row">
              <view class="form-label">文本转语音 <u-icon name="question-circle" size="16" color="#bbb" style="margin-left: 4px;" /></view>
              <u-switch v-model="assistantForm.tts" />
            </view>
            <view class="form-row align-top">
              <view class="form-label required">知识库 <u-icon name="question-circle" size="16" color="#bbb" style="margin-left: 4px;" /></view>
              <view class="knowledge-base-container">
                <view class="knowledge-base-header">
                  <text>可用知识库列表</text>
                </view>
                <view class="knowledge-base-list">
                  <view 
                    v-for="item in datasetListIds" 
                    :key="item.id" 
                    class="knowledge-base-item" 
                    :class="{ 'selected': assistantForm.dataset_ids.includes(item.id) }"
                  >
                    <view class="knowledge-name-wrapper" @tap="handleKnowledgeBaseToggle(item.id)">
                      <checkbox :checked="assistantForm.dataset_ids.includes(item.id)" />
                      <text class="knowledge-name">{{ item.name }}</text>
                    </view>
                  </view>
                  <view v-if="datasetListIds.length === 0" class="empty-tip">
                    暂无可用知识库
                  </view>
                </view>
                <view class="knowledge-base-selected">
                  <text>已选择 {{ assistantForm.dataset_ids.length }} 个知识库</text>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view v-if="activeTab === 'prompt'" class="tab-content">
          <view style="padding: 24px;">
            <view class="form-row">
              <view class="form-label">相似度阈值</view>
              <u-input v-model="assistantForm.prompt.similarity_threshold" type="number" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">关键词相似度权重</view>
              <u-input v-model="assistantForm.prompt.keywords_similarity_weight" type="number" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">检索结果数量</view>
              <u-input v-model="assistantForm.prompt.top_n" type="number" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">重排序模型</view>
              <u-input v-model="assistantForm.prompt.rerank_model" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">重排序后保留结果数</view>
              <u-input v-model="assistantForm.prompt.top_k" type="number" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">提示词</view>
              <u-textarea v-model="assistantForm.prompt.prompt" style="flex:1;" />
            </view>
          </view>
        </view>
        <view v-if="activeTab === 'model'" class="tab-content">
          <view style="padding: 24px;">
            <view class="form-row">
              <view class="form-label">模型名称</view>
              <u-input v-model="assistantForm.llm.model_name" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">Top P</view>
              <u-input v-model="assistantForm.llm.top_p" type="number" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">存在惩罚</view>
              <u-input v-model="assistantForm.llm.presence_penalty" type="number" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">频率惩罚</view>
              <u-input v-model="assistantForm.llm.frequency_penalty" type="number" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">最大Token数</view>
              <u-input v-model="assistantForm.llm.max_token" type="number" style="flex:1;" />
            </view>
            <view class="form-row">
              <view class="form-label">温度</view>
              <u-input v-model="assistantForm.llm.temperature" type="number" style="flex:1;" />
            </view>
          </view>
        </view>
        
        <!-- 添加提交按钮 -->
        <view class="form-actions">
          <u-button type="primary" @tap="isEditMode ? updateAssistantData() : createAssistant()">
            {{ isEditMode ? '修改助理' : '创建助理' }}
          </u-button>
          <u-button type="default" @tap="closeAssistantPopup" style="margin-left: 12px;">取消</u-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { createAssistantResponse } from '@/commoms/assistant/createAssistantResponse'
import { listDatasets } from '@/commoms/dataset/listDatasets'
import { onMounted } from 'vue'
import uInput from 'uview-plus/components/u-input/u-input.vue'
import uUpload from 'uview-plus/components/u-upload/u-upload.vue'
import uTextarea from 'uview-plus/components/u-textarea/u-textarea.vue'
import uSwitch from 'uview-plus/components/u-switch/u-switch.vue'
import uIcon from 'uview-plus/components/u-icon/u-icon.vue'
import uSelect from 'uview-plus/components/u-select/u-select.vue'
import uCheckboxGroup from 'uview-plus/components/u-checkbox-group/u-checkbox-group.vue'
import uCheckbox from 'uview-plus/components/u-checkbox/u-checkbox.vue'
import uButton from 'uview-plus/components/u-button/u-button.vue'
import { listAssistants } from '@/commoms/assistant/listAssistants'
import { deleteAssistant } from '@/commoms/assistant/deleteAssistant'
import { updateAssistant } from '@/commoms/assistant/updateAssistant'
import { uploadFile as uploadFileApi } from '@/commoms/upLoadController/uploadFile'

const dataset = ref({ name: '', knowledge: '', avatar: '' })
// 添加知识库ID和名称的存储
const knowledgeBaseInfo = ref({ id: '', name: '' })

onLoad((options) => {
  console.log('接收到的完整options:', options);
  
  // 对接收到的参数进行URL解码
  const decodedKbName = options.kbName ? decodeURIComponent(options.kbName) : '';
  
  dataset.value = {
    name: decodedKbName || '',
    knowledge: options.knowledge ? decodeURIComponent(options.knowledge) : '',
    avatar: options.avatar ? decodeURIComponent(options.avatar) : 'https://i.pravatar.cc/40?img=3'
  }
  
  // 存储知识库ID和名称
  knowledgeBaseInfo.value = {
    id: options.kbId || '',
    name: decodedKbName || 'SGNER的知识库'
  }
  
  console.log('处理后的知识库信息:', knowledgeBaseInfo.value);
})
onMounted(async () => {
  try {
    // 登录逻辑 - 添加环境检测
    console.log('检测当前运行环境...');
    
    // 获取当前平台信息
    const systemInfo = uni.getSystemInfoSync();
    console.log('系统信息:', systemInfo);
    
    // 检测是否在微信小程序中
    const isMpWeixin = process.env.UNI_PLATFORM === 'mp-weixin' || 
                      (systemInfo.mp && systemInfo.mp.weixin) || 
                      systemInfo.uniPlatform === 'mp-weixin';
    
    console.log('是否微信小程序环境:', isMpWeixin);
    console.log('UNI_PLATFORM:', process.env.UNI_PLATFORM);
    console.log('VUE_APP_PLATFORM:', process.env.VUE_APP_PLATFORM);
    
    if (isMpWeixin) {
      // 微信小程序环境
      console.log('确认微信小程序环境，调用wx.login');
      try {
        uni.login({
          provider: 'weixin',
          success: function(loginRes) {
            console.log('微信登录成功:', loginRes);
            const code = loginRes.code;
            console.log('登录凭证code:', code);
            handleLoginSuccess(code);
          },
          fail: function(err) {
            console.error('微信登录失败:', err);
          }
        });
      } catch (wxLoginError) {
        console.error('wx.login调用失败:', wxLoginError);
      }
    } else {
      // H5或其他环境
      console.log('H5或其他环境，使用Web方式获取登录凭证');
      // H5环境下获取登录凭证
      getH5LoginCredentials().then(code => {
        console.log('H5登录凭证:', code);
        if (code) {
          handleLoginSuccess(code);
        }
      });
    }
    
    // 获取知识库列表
    const res = await listDatasets(params);
    console.log('日志22');
    console.log(res.data);
    console.log('日志23');
    if (res && res.data && res.data.data) {
      // 将所有知识库ID存入datasetListIds
      datasetListIds.value = res.data.data.map(item => ({ id: item.id, name: item.name }))
      
      // 将所有知识库ID存入assistantForm.dataset_ids
      assistantForm.value.dataset_ids = datasetListIds.value.map(item => item.id)
      
      console.log('知识库列表:', datasetListIds.value)
      console.log('已选择的知识库IDs:', assistantForm.value.dataset_ids)
    } else {
      console.error('获取知识库列表失败:', res)
      // 添加测试数据
      datasetListIds.value = [
        { id: 'asdd', name: 'asdd' },
        { id: 'SGNER的知识库', name: 'SGNER的知识库' }
      ]
      assistantForm.value.dataset_ids = ['asdd', 'SGNER的知识库']
    }
    
    // 获取助手列表
    const assistantParams = {
      page: 1,
      page_size: 10,
   
    }
    const assistantRes = await listAssistants(assistantParams)
    console.log('获取助手列表成功:', assistantRes)
    if (assistantRes && assistantRes.data) {
      // 更新助手列表，为每个助手添加showContextMenu属性
      assistantList.value = (assistantRes.data.data || []).map(assistant => ({
        ...assistant,
        showContextMenu: false
      }));
      
      // 提取所有助手的ID并存储
      assistantIds.value = assistantList.value.map(assistant => assistant.id)
      console.log('所有助手ID:', assistantIds.value)
    }
  } catch (error) {
    console.error('获取数据出错:', error)
    // 添加测试数据
    datasetListIds.value = [
      { id: 'asdd', name: 'asdd' },
      { id: 'SGNER的知识库', name: 'SGNER的知识库' }
    ]
    assistantForm.value.dataset_ids = ['asdd', 'SGNER的知识库']
  }
  console.log('打印日志3')
  console.log(datasetListIds.value)
})
const params = {
    page: 1,
    page_size: 10
  }
const showAssistantPopup = ref(false)
const activeTab = ref('setting')
const datasetListIds = ref([])
const assistantForm = ref({
  name: '',
  description: '',
  avatarList: [],
  emptyReply: '',
  greeting: '你好！我是你的助理，有什么可以帮助你的吗？',
  showCitation: true,
  keywordAnalysis: false,
  tts: false,
  dataset_ids: [],
  llm: {
    model_name: "string",
    top_p: 0.0,
    presence_penalty: 0.0,
    frequency_penalty: 0.0,
    max_token: 0.0,
    temperature: 0.0
  },
  prompt: {
    similarity_threshold: 0.0,
    keywords_similarity_weight: 0.0,
    top_n: 0.0,
    rerank_model: "string",
    top_k: 0.0,
    empty_response: "",
    show_quote: true,
    variables: [
      {
        key: "string",
        optional: true
      }
    ],
    opener: "",
    prompt: "string"
  }
})
const knowledgeBaseOptions = computed(() =>
  datasetListIds.value.map(item => ({ label: item.name, value: item.id }))
)

function openAssistantPopup() {
  // 添加默认测试数据，确保知识库选项显示
  if (datasetListIds.value.length === 0) {
    datasetListIds.value = [
      { id: 'asdd', name: 'asdd' },
      { id: 'SGNER的知识库', name: 'SGNER的知识库' }
    ];
  }
  
  // 如果没有选中的知识库，默认选中所有知识库
  if (assistantForm.value.dataset_ids.length === 0) {
    assistantForm.value.dataset_ids = datasetListIds.value.map(item => item.id);
  }
  
  showAssistantPopup.value = true;
  activeTab.value = 'setting';
  console.log('打开弹窗，当前知识库列表:', datasetListIds.value);
  console.log('当前选中的知识库:', assistantForm.value.dataset_ids);
}
function closeAssistantPopup() {
  showAssistantPopup.value = false
  // 重置编辑模式
  isEditMode.value = false
  editingAssistantId.value = ''
  // 重置表单数据
  assistantForm.value = {
    name: '',
    description: '',
    avatarList: [],
    emptyReply: '',
    greeting: '你好！我是你的助理，有什么可以帮助你的吗？',
    showCitation: true,
    keywordAnalysis: false,
    tts: false,
    dataset_ids: [],
    llm: {
      model_name: "string",
      top_p: 0.0,
      presence_penalty: 0.0,
      frequency_penalty: 0.0,
      max_token: 0.0,
      temperature: 0.0
    },
    prompt: {
      similarity_threshold: 0.0,
      keywords_similarity_weight: 0.0,
      top_n: 0.0,
      rerank_model: "string",
      top_k: 0.0,
      empty_response: "",
      show_quote: true,
      variables: [
        {
          key: "string",
          optional: true
        }
      ],
      opener: "",
      prompt: "string"
    }
  }
}

function onAvatarUpload(event) {
  assistantForm.value.avatarList = event.fileList
}

async function createAssistant() {
  console.log('打印日志66')
  console.log(assistantForm.value.dataset_ids)
  console.log('打印日志33')
  
  // 将Proxy包装的数组转换为普通字符串数组
  const datasetIdsArray = Array.from(assistantForm.value.dataset_ids).map(id => String(id))
  
  // 构造请求对象
  const params = {
    name: assistantForm.value.name,
    avatar: assistantForm.value.avatarList.length > 0 ? assistantForm.value.avatarList[0].url : '',
    dataset_ids: datasetIdsArray,
    llm: {
      model_name: assistantForm.value.llm.model_name,
      top_p: 0.0,
      presence_penalty: 0.0,
      frequency_penalty: 0.0,
      max_token: 0.0,
      temperature: 0.0
    },
    prompt: {
      similarity_threshold: assistantForm.value.prompt.similarity_threshold || 0.2,
      keywords_similarity_weight: assistantForm.value.prompt.keywords_similarity_weight || 0.7,
      top_n: assistantForm.value.prompt.top_n || 8,
      top_k: assistantForm.value.prompt.top_k || 0,
      empty_response: assistantForm.value.emptyReply || "知识库中未找到您要的答案！",
      show_quote: assistantForm.value.showCitation,
      variables: [
        {
          key: "string",
          optional: true
        }
      ],
      opener: assistantForm.value.greeting || "你好！我是你的助理，有什么可以帮助你的吗？",
      prompt: assistantForm.value.prompt.prompt || ""
    }
  }
  
  // 打印参数
  console.log('创建参数:')
  console.log(params)
  
  // 然后调用API
  const res = await createAssistantResponse(params)
  
  if (res.code === 200) {
    closeAssistantPopup()
    console.log('日志24')
    console.log(res.data)
    console.log('日志25')
    // 刷新助手列表
    const assistantParams = {
      page: 1,
      page_size: 10
    }
    const assistantRes = await listAssistants(assistantParams)
    if (assistantRes && assistantRes.data) {
      assistantList.value = assistantRes.data.data || []
    }
    // 显示成功提示
    uni.showToast({
      title: '创建成功',
      icon: 'success'
    })
  }
}

function handleKnowledgeBaseToggle(id) {
  console.log('切换知识库选择:', id);
  const index = assistantForm.value.dataset_ids.indexOf(id);
  if (index === -1) {
    // 如果不在列表中，添加
    assistantForm.value.dataset_ids.push(id);
  } else {
    // 如果在列表中，移除
    assistantForm.value.dataset_ids.splice(index, 1);
  }
  console.log('选中的知识库IDs:', assistantForm.value.dataset_ids);
}

// 在data部分添加assistantList变量
const assistantList = ref([])
// 添加存储助手ID的数组
const assistantIds = ref([])

// 添加当前选中的助手
const currentAssistant = ref(null)

// 添加编辑模式标志
const isEditMode = ref(false)
// 存储正在编辑的助理ID
const editingAssistantId = ref('')

// 选择助手的方法
function selectAssistant(assistant) {
  currentAssistant.value = assistant
  // 这里可以添加选择助手后的其他操作，比如加载对话历史等
  console.log('选择了助手:', assistant)
  
  // 更新右侧显示
  if (assistant) {
    dataset.value = {
      name: assistant.name || '',
      knowledge: assistant.description || '',
      avatar: assistant.avatar || 'https://i.pravatar.cc/40?img=3'
    }
  }
}

function getDatasetNames(datasetIds) {
  if (!datasetIds || !datasetIds.length) return '无知识库';
  
  // Filter datasetListIds to only include datasets that are in the assistant's dataset_ids
  const matchingDatasets = datasetListIds.value.filter(dataset => 
    datasetIds.includes(dataset.id)
  );
  
  // Map to dataset names and join with commas
  if (matchingDatasets.length > 0) {
    return matchingDatasets.map(dataset => dataset.name).join(', ');
  }
  
  // If no matching datasets found but ids exist, just return the ids
  return datasetIds.join(', ');
}

// 添加存储选中助手ID的数组
const selectedAssistantIds = ref([])

// 切换选中状态的函数
function toggleAssistantSelection(id) {
  const index = selectedAssistantIds.value.indexOf(id)
  if (index === -1) {
    // 如果不在选中列表中，添加
    selectedAssistantIds.value.push(id)
  } else {
    // 如果在选中列表中，移除
    selectedAssistantIds.value.splice(index, 1)
  }
  console.log('选中的助手IDs:', selectedAssistantIds.value)
}

// 编辑助理的方法
function editAssistant(assistant) {
  try {
    console.log('editAssistant called', assistant);
    
    // 设置编辑模式
    isEditMode.value = true
    editingAssistantId.value = assistant.id
    
    // 填充表单数据
    assistantForm.value.name = assistant.name || ''
    assistantForm.value.description = assistant.description || ''
    
    // 设置选中的知识库
    if (assistant.datasets && assistant.datasets.length) {
      assistantForm.value.dataset_ids = assistant.datasets.map(d => d.id)
    }
    
    // 设置LLM参数
    if (assistant.llm) {
      assistantForm.value.llm = {
        model_name: assistant.llm.model_name || 'string',
        top_p: assistant.llm.top_p || 0.0,
        presence_penalty: assistant.llm.presence_penalty || 0.0,
        frequency_penalty: assistant.llm.frequency_penalty || 0.0,
        max_token: assistant.llm.max_tokens || 0.0,
        temperature: assistant.llm.temperature || 0.0
      }
    }
    
    // 设置提示词参数
    if (assistant.prompt) {
      assistantForm.value.prompt = {
        similarity_threshold: assistant.prompt.similarity_threshold || 0.2,
        keywords_similarity_weight: assistant.prompt.keywords_similarity_weight || 0.7,
        top_n: assistant.prompt.top_n || 8,
        top_k: assistant.prompt.top_k || 0,
        empty_response: assistant.prompt.empty_response || '知识库中未找到您要的答案！',
        show_quote: assistant.prompt.show_quote !== undefined ? assistant.prompt.show_quote : true,
        variables: assistant.prompt.variables || [{ key: 'string', optional: true }],
        opener: assistant.prompt.opener || '你好！我是你的助理，有什么可以帮助你的吗？',
        prompt: assistant.prompt.prompt || ''
      }
    }
    
    // 设置其他参数
    assistantForm.value.emptyReply = assistant.prompt?.empty_response || '知识库中未找到您要的答案！'
    assistantForm.value.greeting = assistant.prompt?.opener || '你好！我是你的助理，有什么可以帮助你的吗？'
    assistantForm.value.showCitation = assistant.prompt?.show_quote !== undefined ? assistant.prompt.show_quote : true
    
    // 打开弹窗
    console.log('Setting showAssistantPopup to true');
    showAssistantPopup.value = true
    activeTab.value = 'setting'
    
    // 手动触发UI更新
    setTimeout(() => {
      console.log('Popup should be visible now, showAssistantPopup =', showAssistantPopup.value);
    }, 100);
  } catch (error) {
    console.error('编辑助理出错:', error);
    uni.showToast({
      title: '编辑操作失败',
      icon: 'none'
    });
  }
}

// 批量删除助手的函数
async function batchDeleteAssistants() {
  if (selectedAssistantIds.value.length === 0) {
    uni.showToast({
      title: '请选择要删除的助手',
      icon: 'none'
    })
    return
  }
  
  // 显示确认对话框
  uni.showModal({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedAssistantIds.value.length} 个助手吗？`,
    success: async function(res) {
      if (res.confirm) {
        try {
          // 使用Promise.all循环删除选中的助手
          const deletePromises = selectedAssistantIds.value.map(id => 
            deleteAssistant(id)
          )
          
          await Promise.all(deletePromises)
          
          // 清空选中列表
          selectedAssistantIds.value = []
          
          // 如果当前选中的助手被删除，清空当前选中
          if (currentAssistant.value && selectedAssistantIds.value.includes(currentAssistant.value.id)) {
            currentAssistant.value = null
          }
          
          // 刷新助手列表，从服务器获取最新数据
          const assistantParams = {
            page: 1,
            page_size: 10
          }
          const assistantRes = await listAssistants(assistantParams)
          if (assistantRes && assistantRes.data) {
            assistantList.value = assistantRes.data.data || []
          }
          
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
        } catch (error) {
          console.error('删除助手出错:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

// 添加更新助理的方法
async function updateAssistantData() {
  // 将Proxy包装的数组转换为普通字符串数组
  const datasetIdsArray = Array.from(assistantForm.value.dataset_ids).map(id => String(id))
  
  // 构造请求对象，与创建助理的参数结构相同
  const params = {
    id: editingAssistantId.value, // 添加ID字段，用于标识要更新的助理
    name: assistantForm.value.name,
    avatar: assistantForm.value.avatarList.length > 0 ? assistantForm.value.avatarList[0].url : '',
    dataset_ids: datasetIdsArray,
    llm: {
      model_name: assistantForm.value.llm.model_name,
      top_p: 0.0,
      presence_penalty: 0.0,
      frequency_penalty: 0.0,
      max_token: 0.0,
      temperature: 0.0
    },
    prompt: {
      similarity_threshold: assistantForm.value.prompt.similarity_threshold || 0.2,
      keywords_similarity_weight: assistantForm.value.prompt.keywords_similarity_weight || 0.7,
      top_n: assistantForm.value.prompt.top_n || 8,
      top_k: assistantForm.value.prompt.top_k || 0,
      empty_response: assistantForm.value.emptyReply || "知识库中未找到您要的答案！",
      show_quote: assistantForm.value.showCitation,
      variables: [
        {
          key: "string",
          optional: true
        }
      ],
      opener: assistantForm.value.greeting || "你好！我是你的助理，有什么可以帮助你的吗？",
      prompt: assistantForm.value.prompt.prompt || ""
    }
  }
  console.log('更新参数:')
  console.log(params)
  console.log('更新参数结束')
  
  try {
    // 先关闭弹窗，确保无论如何弹窗都会关闭
    closeAssistantPopup()
    
    // 调用更新API
    const res = await updateAssistant(params)
    console.log('更新响应:', res)
    
    if (res.code === 20000) {
      // 刷新助手列表
      const assistantParams = {
        page: 1,
        page_size: 10
      }
      const assistantRes = await listAssistants(assistantParams)
      if (assistantRes && assistantRes.data) {
        assistantList.value = assistantRes.data.data || []
      }
      // 显示成功提示
      uni.showToast({
        title: '修改成功',
        icon: 'success'
      })
    } else {
      // 显示错误提示
      uni.showToast({
        title: res.msg || '修改失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('修改助理出错:', error)
    uni.showToast({
      title: '修改失败',
      icon: 'none'
    })
  }
}

// 添加删除单个助手的方法
async function deleteAssistantById(id) {
  try {
    // 显示确认对话框
    uni.showModal({
      title: '确认删除',
      content: '确定要删除此助手吗？',
      success: async function(res) {
        if (res.confirm) {
          await deleteAssistant(id);
          
          // 刷新助手列表，从服务器获取最新数据
          const assistantParams = {
            page: 1,
            page_size: 10
          }
          const assistantRes = await listAssistants(assistantParams)
          if (assistantRes && assistantRes.data) {
            assistantList.value = assistantRes.data.data || []
          }
          
          // 如果当前选中的助手被删除，清空当前选中
          if (currentAssistant.value && currentAssistant.value.id === id) {
            currentAssistant.value = null;
          }
          
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  } catch (error) {
    console.error('删除助手出错:', error);
    uni.showToast({
      title: '删除失败',
      icon: 'error'
    });
  }
}

const messageText = ref('')
const fileList = ref([])

// 打开文件选择器
function openFileSelector() {
  console.log('==== openFileSelector 开始执行 ====');
  // 使用防抖处理，避免重复触发
  if (typeof window !== 'undefined' && window._isFileUploading) {
    console.log('文件上传中，请等待...');
    return;
  }
  
  // 初始化标志变量，确保它存在
  if (typeof window !== 'undefined') {
    window._isFileUploading = true;
  }
  
  // 微信小程序环境
  // #ifdef MP-WEIXIN
  uni.chooseMessageFile({
    count: 1,
    type: 'all',
    extension: ['pdf', 'doc', 'docx', 'txt', 'jpg', 'jpeg', 'png'],
    success: function(res) {
      console.log('选择文件成功:', res);
      if (res.tempFiles && res.tempFiles.length > 0) {
        const fileInfo = res.tempFiles[0];
        const filePath = fileInfo.path;
        const originalFileName = fileInfo.name;
        
        if (originalFileName) {
          // 检查文件扩展名
          const lastDotIndex = originalFileName.lastIndexOf('.');
          if (lastDotIndex !== -1) {
            const extension = originalFileName.substring(lastDotIndex + 1).toLowerCase();
            const supportedExtensions = ['pdf', 'doc', 'docx', 'txt', 'jpg', 'jpeg', 'png'];
            if (supportedExtensions.includes(extension)) {
              handleFileUpload(filePath, originalFileName);
            } else {
              uni.showToast({
                title: '不支持的文件类型',
                icon: 'none'
              });
            }
          }
        }
      }
    },
    fail: function(err) {
      console.error('选择文件失败:', err);
      uni.showToast({
        title: '选择文件失败',
        icon: 'none'
      });
    },
    complete: function() {
      setTimeout(() => {
        if (typeof window !== 'undefined') {
          window._isFileUploading = false;
        }
      }, 1000);
    }
  });
  // #endif
  
  // H5环境
  // #ifdef H5
  // 创建一个隐藏的file input
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.pdf,.doc,.docx,.txt,.jpg,.jpeg,.png';
  input.style.display = 'none';
  
  input.onchange = function(e) {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      const filePath = URL.createObjectURL(file);
      handleFileUpload(filePath, file.name);
    }
    // 清理DOM
    document.body.removeChild(input);
  };
  
  document.body.appendChild(input);
  input.click();
  
  // 完成后重置上传状态
  setTimeout(() => {
    if (typeof window !== 'undefined') {
      window._isFileUploading = false;
    }
  }, 1000);
  // #endif
  
  // App环境
  // #ifdef APP-PLUS
  uni.chooseImage({
    count: 1,
    success: function(res) {
      if (res.tempFilePaths && res.tempFilePaths.length > 0) {
        const filePath = res.tempFilePaths[0];
        const fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
        handleFileUpload(filePath, fileName);
      }
    },
    fail: function(err) {
      console.error('选择文件失败:', err);
      uni.showToast({
        title: '选择文件失败',
        icon: 'none'
      });
    },
    complete: function() {
      setTimeout(() => {
        if (typeof window !== 'undefined') {
          window._isFileUploading = false;
        }
      }, 1000);
    }
  });
  // #endif
}

function getMimeType(filePath, originalFileName) {
  withCtx.login

}
// 修改上传文件函数使用uploadFileApi
async function handleFileUpload(filePath, originalFileName) {
  console.log('==== handleFileUpload 开始执行 ====');
  if (!filePath) {
    console.error('文件路径为空');
    uni.showToast({
      title: '文件路径为空',
      icon: 'none'
    });
    return;
  }
  
  try {
    console.log('准备上传文件:', filePath);
    console.log('原始文件名:', originalFileName);
    
    uni.showLoading({
      title: '上传中...'
    });
    
    // 获取文件大小
    let fileSize = 0;
    let fileContent = null;
    
    // 尝试获取文件信息
    try {
      const fileInfo = await new Promise((resolve, reject) => {
        uni.getFileInfo({
          filePath: filePath,
          success: res => resolve(res),
          fail: err => reject(err)
        });
      });
      fileSize = fileInfo.size;
      console.log('获取到文件大小:', fileSize);
      
      // 读取文件内容
      fileContent = await new Promise((resolve, reject) => {
        // #ifdef H5
        if (filePath.startsWith('blob:')) {
          // H5环境，处理blob URL
          fetch(filePath)
            .then(response => response.arrayBuffer())
            .then(buffer => resolve(new Uint8Array(buffer)))
            .catch(err => reject(err));
        } else {
        // #endif
          // 小程序环境或其他环境
          uni.getFileSystemManager().readFile({
            filePath: filePath,
            success: res => resolve(res.data),
            fail: err => reject(err)
          });
        // #ifdef H5
        }
        // #endif
      });
      
      console.log('文件内容读取成功，准备切片');
    } catch (e) {
      console.error('获取文件信息失败:', e);
      // 如果获取失败，使用默认值
      fileSize = 0;
      throw new Error('读取文件失败: ' + e.message);
    }
    
    // 文件切片大小，设置为5MB
    const CHUNK_SIZE = 5 * 1024 * 1024;
    
    // 计算总切片数
    const totalChunks = Math.ceil(fileSize / CHUNK_SIZE);
    console.log(`文件大小: ${fileSize}字节, 切片大小: ${CHUNK_SIZE}字节, 总切片数: ${totalChunks}`);
    
    // 生成唯一的文件ID
    const fileId = 'file_' + Date.now();
    
    // 构建基础上传参数
    const baseUploadOptions = {
      fileId: fileId,
      chunkIndex: 0,
      // 使用从index.vue传递过来的知识库信息
      kbName: knowledgeBaseInfo.value.name || "SGNER的知识库",
      kbId: knowledgeBaseInfo.value.id || "01bb4630f90011ef8a750242ac120006",
      totalChunks: totalChunks,
      originalFileName: originalFileName
    };
    
    console.log('上传参数中的知识库信息:', {
      kbName: baseUploadOptions.kbName,
      kbId: baseUploadOptions.kbId
    });
    
    // 修改为顺序上传切片
    const uploadResults = [];
    
    // 顺序上传所有切片
    for (let i = 0; i < totalChunks; i++) {
      // 计算当前切片的起始位置和结束位置
      const start = i * CHUNK_SIZE;
      const end = Math.min(start + CHUNK_SIZE, fileSize);
      
      // 提取当前切片数据
      const chunk = fileContent.slice(start, end);
      
      // 将二进制数据转换为Base64字符串
      let base64Chunk = '';
      
      // #ifdef H5
      // H5环境下，使用btoa将二进制转为base64
      if (typeof chunk === 'object' && chunk instanceof Uint8Array) {
        // 将Uint8Array转换为字符串
        let binary = '';
        const bytes = new Uint8Array(chunk);
        const len = bytes.byteLength;
        for (let j = 0; j < len; j++) {
          binary += String.fromCharCode(bytes[j]);
        }
        base64Chunk = btoa(binary);
      } else {
        base64Chunk = btoa(String.fromCharCode.apply(null, new Uint8Array(chunk)));
      }
      // #endif
      
      // #ifdef MP-WEIXIN
      // 微信小程序环境下，使用wx.arrayBufferToBase64
      if (typeof wx !== 'undefined' && wx.arrayBufferToBase64) {
        base64Chunk = wx.arrayBufferToBase64(chunk);
      }
      // #endif
      
      console.log(`准备上传第${i+1}/${totalChunks}个切片, 大小: ${end-start}字节`);
      console.log(`第${i+1}切片的前20个字符: ${base64Chunk.substring(0, 20)}...`);
      
      // 将Base64转回二进制字符串 (string(binary))
      let binaryString = '';
      try {
        binaryString = atob(base64Chunk);
      } catch (e) {
        console.error('Base64解码失败:', e);
        // 如果解码失败，继续使用Base64字符串
        binaryString = base64Chunk;
      }
      
      // 构建当前切片的上传参数
      const chunkUploadOptions = {
        ...baseUploadOptions,
        chunkIndex: i,  // 使用当前循环索引作为切片索引
        body: {
          chunk: binaryString // 使用二进制字符串而不是Base64
        },
        // 标记是否是第一个切片，只有第一个切片需要初始化
        isFirstChunk: i === 0 ? true : false,
        // 添加最后一个切片的标记
        isLastChunk: i === totalChunks - 1 ? true : false
      };
      
      console.log(`开始上传第${i+1}/${totalChunks}个切片，索引为: ${i}`);
      
      try {
        // 使用await等待每个切片上传完成后再上传下一个
        const result = await uploadFileApi(filePath, chunkUploadOptions);
        console.log(`第${i+1}/${totalChunks}个切片上传成功:`, result);
        
        // 如果是第一个切片，保存返回的fileId用于后续切片
        if (i === 0 && result.data && result.data.fileId) {
          baseUploadOptions.fileId = result.data.fileId;
          console.log('从第一个切片响应中获取到fileId:', baseUploadOptions.fileId);
        }
        
        uploadResults.push(result);
      } catch (err) {
        console.error(`第${i+1}/${totalChunks}个切片上传失败:`, err);
        throw new Error(`切片${i+1}上传失败: ${err.message}`);
      }
    }
    
    console.log('所有切片上传完成:', uploadResults);
    
    // 使用最后一个切片的上传结果作为整体上传结果
    const apiResult = uploadResults[uploadResults.length - 1];
    
    if (apiResult && apiResult.code === 200) {
      // 将文件添加到列表
      fileList.value.push({
        url: apiResult.data?.url || '',
        name: originalFileName || apiResult.data?.filename || 'document',
        size: apiResult.data?.size || fileSize,
        fileId: baseUploadOptions.fileId,
        kbId: baseUploadOptions.kbId,
        kbName: baseUploadOptions.kbName
      });
      
      uni.showToast({
        title: '上传成功',
        icon: 'success'
      });
    } else {
      // 显示错误信息
      let errorMsg = apiResult?.msg || '上传失败';
      if (apiResult?.error) {
        errorMsg += ': ' + apiResult.error;
      }
      
      uni.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 3000
      });
      
      console.error('上传失败详情:', apiResult);
    }
    
    uni.hideLoading();
  } catch (error) {
    console.error('文件上传错误:', error);
    uni.hideLoading();
    uni.showToast({
      title: error.message || '上传出错',
      icon: 'none',
      duration: 3000
    });
  }
}

// 添加这些变量
const messageContent = ref('')
const uploadedFiles = ref([])

// 修改sendMessage函数
function sendMessage() {
  if (!messageText.value.trim() && fileList.value.length === 0) {
    return;
  }
  
  console.log('发送消息:', messageText.value);
  console.log('附带文件:', fileList.value);
  
  // 保存消息内容以显示在界面上
  messageContent.value = messageText.value;
  uploadedFiles.value = [...fileList.value];
  
  // 在这里添加你的发送消息逻辑
  
  // 清空输入框和待上传列表
  messageText.value = '';
  fileList.value = [];
}

// 添加处理登录成功的函数
async function handleLoginSuccess(code) {
  try {
    console.log('处理登录成功，code:', code);
    
    // 使用wx.request发送code到后端
    wx.request({
      url: `http://74ac341c.r3.cpolar.top/wx/login/sessionId/${code}`,
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        console.log('服务器登录成功:', res.data);
        console.log('打印日志')
        console.log(res.data.data.jwt)
        console.log('打印日志')
        // 处理服务器返回的数据，如保存token等
        if (res.data.data) {
          // 存储用户登录状态和token
          console.log('打印日志')
          console.log(res.data.data)
          uni.setStorageSync('token', res.data.data.jwt);
          uni.setStorageSync('userInfo', res.data.data.user.username);
          
          // 登录成功后的业务逻辑
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          });
        }
      },
      fail: function(err) {
        console.error('服务器登录失败:', err);
        uni.showToast({
          title: '登录失败',
          icon: 'none'
        });
      }
    });
  } catch (error) {
    console.error('处理登录失败:', error);
  }
}

// 获取H5环境的登录凭证
async function getH5LoginCredentials() {
  try {
    console.log('获取H5环境登录凭证');
    
    // 方法1: 从URL参数中获取code (适用于OAuth重定向)
    const urlParams = new URLSearchParams(window.location.search);
    const codeFromUrl = urlParams.get('code');
    if (codeFromUrl) {
      console.log('从URL获取到code:', codeFromUrl);
      return codeFromUrl;
    }
    
    // 方法2: 从localStorage中获取已存储的token
    const token = uni.getStorageSync('token');
    if (token) {
      console.log('从storage获取到token');
      return token;
    }
    
    // 方法3: 使用第三方OAuth登录获取code (例如微信网页授权)
    // 这需要在微信公众平台配置，通常涉及跳转到授权页面
    // 以微信网页授权为例
    const isWechatBrowser = navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1;
    if (isWechatBrowser) {
      // 在微信浏览器中
      console.log('检测到微信浏览器，可以使用微信网页授权');
      // 可以实现微信网页授权，获取code
      // 注意：这通常需要服务器配合，以下仅为示例
      /*
      const appId = 'your_appid';
      const redirectUri = encodeURIComponent(window.location.href);
      const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
      
      // 如果当前URL没有code参数，则跳转到授权页面
      if (!codeFromUrl) {
        window.location.href = authUrl;
        return null;
      }
      */
    }
    
    // 方法4: 如果都没有，可以显示登录界面，让用户手动登录
    console.log('没有找到登录凭证，需要用户手动登录');
    // showLoginModal(); // 显示登录弹窗
    
    // 为了演示，生成一个临时的凭证
    const tempCode = 'h5_temp_code_' + Date.now();
    console.log('生成临时凭证:', tempCode);
    return tempCode;
    
  } catch (error) {
    console.error('获取H5登录凭证出错:', error);
    return null;
  }
}

// H5环境登录处理
function handleH5Login() {
  console.log('执行H5环境登录逻辑');
  // 这里可以实现H5环境的登录方式
  // 例如：
  // 1. 使用cookie/session登录
  // 2. 使用OAuth第三方登录
  // 3. 使用账号密码登录表单
  
  // 模拟登录成功
  const mockUserInfo = {
    userId: 'h5_user_' + Date.now(),
    userName: 'H5用户'
  };
  
  // 存储用户信息
  uni.setStorageSync('userInfo', JSON.stringify(mockUserInfo));
  console.log('H5登录成功，用户信息:', mockUserInfo);
}

// 通用环境登录处理
function handleGenericLogin() {
  console.log('执行通用环境登录逻辑');
  // 实现适用于当前环境的登录方式
  // 可以根据实际情况选择合适的登录方式
  
  // 模拟登录成功
  const mockUserInfo = {
    userId: 'generic_user_' + Date.now(),
    userName: '通用用户'
  };
  
  // 存储用户信息
  uni.setStorageSync('userInfo', JSON.stringify(mockUserInfo));
  console.log('通用登录成功，用户信息:', mockUserInfo);
}
</script>

<style scoped>
/* 基本样式 */
.dialog-container {
  display: flex;
  height: 100vh;
  background: #f7f8fa;
}

/* 微信小程序特定样式 */
/* #ifdef MP-WEIXIN */
.dialog-container {
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.sidebar {
  width: 100%;
  height: auto;
  max-height: 30vh;
  border-right: none;
  border-bottom: 1px solid #eee;
  overflow-y: auto;
}

.chat-list {
  width: 100%;
  height: auto;
  max-height: 20vh;
  border-right: none;
  border-bottom: 1px solid #eee;
  overflow-y: auto;
}

.chat-content {
  flex: 1;
  height: 50vh;
  overflow-y: auto;
  padding: 16px;
}

.assistant-popup-content {
  background: #fff;
  border-radius: 12px;
  width: 90%;
  max-width: 90vw;
  max-height: 80vh;
  padding: 0 0 24px 0;
  overflow-y: auto;
}

.form-row {
  flex-wrap: wrap;
}

.form-label {
  width: 100%;
  margin-bottom: 8px;
}

.knowledge-base-list {
  max-height: 200px;
}
/* #endif */

/* H5特定样式 */
/* #ifdef H5 */
.dialog-container {
  flex-direction: row;
}

.sidebar {
  width: 160px;
  background: #fff;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 0;
}

.chat-list {
  width: 140px;
  background: #f9f9f9;
  border-right: 1px solid #eee;
  padding: 16px 0;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 24px 32px;
  background: #fff;
}

.assistant-popup-content {
  background: #fff;
  border-radius: 12px;
  min-width: 600px;
  min-height: 400px;
  max-height: 90vh;
  padding: 0 0 24px 0;
  overflow-y: auto;
}
/* #endif */

/* 通用样式 */
.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0 12px;
  margin-bottom: 16px;
}

.sidebar-title {
  font-weight: bold;
}

.assistant-list {
  width: 100%;
}

.assistant-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 8px;
  margin-bottom: 8px;
}

.assistant-checkbox {
  margin-right: 8px;
  flex-shrink: 0;
}

.assistant-content {
  display: flex;
  align-items: center;
  flex: 1;
  overflow: hidden;
}

.assistant-item.active, .assistant-item:hover {
  background: #f0f6ff;
}

.assistant-item u-avatar {
  margin-right: 8px;
}

.assistant-actions {
  margin-left: auto;
  opacity: 1;
}

.assistant-item:hover .assistant-actions {
  opacity: 1;
}

.chat-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: bold;
  margin-bottom: 16px;
  padding: 0 12px;
}

.chat-item {
  padding: 8px 12px;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
}

.chat-item.active, .chat-item:hover {
  background: #e6f7ff;
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: bold;
  font-size: 1.1rem;
  margin-bottom: 18px;
}

.chat-question {
  color: #333;
}

.chat-message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.chat-message.self {
  flex-direction: row-reverse;
}

.message-bubble {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 12px 16px;
  margin: 0 12px;
  max-width: 60%;
  color: #222;
  font-size: 1rem;
}

.chat-input {
  margin-top: auto;
  display: flex;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

/* #ifdef MP-WEIXIN */
.chat-input {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 12px;
  z-index: 10;
}
/* #endif */

.input {
  flex: 1;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 8px 12px;
  margin-right: 12px;
  font-size: 1rem;
}

.chat-input-actions {
  display: flex;
  align-items: center;
}

.upload-icon {
  margin-right: 8px;
  padding: 4px;
  cursor: pointer;
  border-radius: 4px;
}

.upload-icon:hover {
  background-color: #f0f0f0;
}

.assistant-popup-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.tab-bar {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 16px;
  position: sticky;
  top: 0;
  background: #fff;
  z-index: 10;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 16px 0;
  cursor: pointer;
  font-weight: bold;
}

.tab.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.tab-content {
  max-height: none;
  overflow-y: auto;
  padding-bottom: 20px;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}

.form-row.align-top {
  align-items: flex-start;
}

.form-label {
  display: flex;
  align-items: center;
  font-weight: bold;
  margin-right: 12px;
  gap: 4px;
  font-size: 15px;
}

.required::before {
  content: '*';
  color: #f56c6c;
  margin-right: 2px;
}

.switch-row {
  justify-content: space-between;
}

.vertical-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.knowledge-base-container {
  width: 100%;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.knowledge-base-header {
  padding: 10px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #ddd;
  font-weight: bold;
}

.knowledge-base-list {
  max-height: 300px;
  overflow-y: auto;
  background-color: #fff;
}

.knowledge-base-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.knowledge-base-item.selected {
  background-color: #f0f7ff;
}

.knowledge-name {
  font-size: 14px;
}

.knowledge-name-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.knowledge-action {
  display: flex;
}

.select-btn {
  padding: 4px 8px;
  font-size: 12px;
  border-radius: 4px;
  border: 1px solid #ddd;
  background-color: #fff;
  cursor: pointer;
}

.select-btn.selected {
  background-color: #409EFF;
  color: #fff;
  border-color: #409EFF;
}

.knowledge-base-selected {
  padding: 10px;
  background-color: #f0f0f0;
  border-top: 1px solid #ddd;
  text-align: right;
  font-size: 12px;
  color: #666;
}

.empty-tip {
  color: #999;
  padding: 10px 0;
  text-align: center;
}

.form-actions {
  display: flex;
  justify-content: center;
  padding: 0 24px;
  margin-top: 16px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
}

.checkbox-text {
  margin-left: 8px;
}

.empty-assistant {
  color: #999;
  padding: 10px 0;
  text-align: center;
}

.edit-button {
  background: none;
  border: none;
  color: #409EFF;
  cursor: pointer;
  font-size: 12px;
  padding: 2px 4px;
}

.context-menu {
  padding: 10px 0;
}

.context-menu-item {
  padding: 12px 16px;
  text-align: center;
  font-size: 16px;
}

.context-menu-item.delete {
  color: #f56c6c;
}

.uploaded-files {
  margin-top: 8px;
  border-top: 1px solid #eaeaea;
  padding-top: 8px;
}

.uploaded-file {
  display: flex;
  align-items: center;
  margin-top: 4px;
  background-color: rgba(64, 158, 255, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
}

.file-name {
  margin-left: 6px;
  font-size: 12px;
  color: #333;
  word-break: break-all;
}
</style>
